package com.example.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
    
    /**
     * 配置安全过滤链，定义请求权限和认证方式
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((requests) -> requests
                                                     .requestMatchers("/").permitAll()
                                                     .anyRequest().authenticated()
            )
            .formLogin((form) -> form
                                     .loginPage("/login")
                                     .permitAll()
            )
            .logout((logout) -> logout.permitAll());
        
        return http.build();
    }
    
    /**
     * 定义一个内存用户，用于测试认证
     */
    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
                               .username("user")
                               .password("password")
                               .roles("USER")
                               .build();
        return new InMemoryUserDetailsManager(user);
    }
}
